import numpy as np
import csv


def load_data(file_path):
    """
    Load city district statistics
    Columns: district, population, avg_rent, area_km2
    Return: 2D array of shape (districts, 3) containing [population, avg_rent, area_km2]
    """
    data = []
    with open(file_path, 'r', encoding='utf-8') as file:
        reader = csv.reader(file)
        next(reader)  # Skip the header row
        for row in reader:
            data.append([float(row[1]), float(row[2]), float(row[3])])
    return np.array(data)


def calculate_statistics(data):
    """
    Calculate city metrics statistics
    Return: Dictionary containing mean, median, variance, std for each metric
    """
    means = np.mean(data, axis=0)
    medians = np.median(data, axis=0)
    variances = np.var(data, axis=0)
    stds = np.std(data, axis=0)
    return {
        'means': means,
        'medians': medians,
        'variances': variances,
        'stds': stds
    }


def print_results(stats):
    """
    Print formatted results with 4-space indentation
    """
    metrics = ['Population', 'Average Rent', 'Area (km²)']
    for metric, mean, med, var, std in zip(metrics,
                                           stats['means'],
                                           stats['medians'],
                                           stats['variances'],
                                           stats['stds']):
        print(f"{metric}:")
        print(f"    Average: {mean:.1f}")
        print(f"    Median: {med:.1f}")
        print(f"    Variance: {var:.1f}")
        print(f"    Standard Deviation: {std:.1f}")


# 写入数据到 beijing.csv 文件
data = [
    ['district', 'population', 'avg_rent', 'area_km2'],
    ['Dongcheng', 860000, 6500, 41],
    ['Xicheng', 1020000, 7200, 46],
    ['Chaoyang', 1450000, 6000, 108]
]
with open('beijing.csv', 'w', newline='', encoding='utf-8') as file:
    writer = csv.writer(file)
    writer.writerows(data)

# Execution flow
city_data = load_data('beijing.csv')
stats = calculate_statistics(city_data)
print_results(stats)

